package com.red.wood.common.util;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

public class CommonUtils {
	
	public static String valueOf(Object object){
		String str = StringUtils.trim(String.valueOf(object));
		boolean check = StringUtils.isBlank(str) || StringUtils.equals(str, "null") || StringUtils.equals(str, "undefined");
		return check ? "" : str;
	}
	
	public static String filteNull(Object object) {
		String str = valueOf(object);
		boolean check = StringUtils.isBlank(str);
		return check ? "0" : str;
	}
	
	/**
	 * 特殊字符校验，防扫描
	 * @param list
	 */
	public static void fieldCheck(List<String[]> list){
		for(String[] str : list){
			if(str.length < 2){
				continue;
			}
			if(str[0].indexOf("'") >= 0 || str[0].indexOf("\"") >= 0){
				throw new RuntimeException("【"+str[1]+"】不能包含单引号和双引号！");
			}
		}
	}
	
	/**
	 * IP校验
	 * @param ip
	 * @return
	 */
	public static boolean isValidIp(String ip){
		String reg = "^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\."
				+ "(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\."
				+ "(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\."
				+ "(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])$";
		Pattern pattern = Pattern.compile(reg);
		Matcher p = pattern.matcher(ip);
		return p.matches();
	}
	
	public static boolean isValidDate(String date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try{
			sdf.setLenient(false);//严格按照给定的格式来校验
			sdf.parse(date);
			return true;
		}catch(Exception e){
			System.out.println(e.getMessage());
			return false;
		}
	}
	
	/**
	 * 转换为Integer类型
	 */
	public static Integer toInteger(Object val){
		return toLong(val).intValue();
	}
	
	/**
	 * 转换为Long类型
	 * @param val
	 * @return
	 */
	public static Long toLong(Object val){
		return toDouble(val).longValue();
	}
	
	/**
	 * 转换为Double类型
	 * @param val
	 * @return
	 */
	public static Double toDouble(Object val){
		if (val == null){
			return -999D;
		}
		try {
			return Double.valueOf(valueOf(val));
		} catch (Exception e) {
			return -999D;
		}
	}
}
